import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // 如果route下面没有mete也没有roles，则视为全部有权限访问
  // 否则 用route的roles来遍历用户的 roles判断是否包含，包含则有权限。
  // 比如 route的权限是 ccc ,ddd  用户的权限是 aaa,bbb,ccc（可以视为3个部门） 则有权限访问， 
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
// 过滤动态的路由
export function filterAsyncRoutes(routes, roles) {
  
  const res = []
  // 遍历筛选路由表，判断是否有权限,有权限则添加
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
      
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // 合并路由（concat拼接路由）
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 创建筛选权限的路由
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      // 如果roles包含了 admin 权限路由直接等于 asyncRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        // 如果不是管理员 则进行路由过滤
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
